package com.wzcl.app.model.dto;

import com.wzcl.app.dao.model.common.Base;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

@Data
public class BaseDto {
   public static final int DESC = 1;
   public static final int ASC = 0;

   Integer id;

   Integer pageSize = 10;

   Integer pageNumber = 0;

   Map<String,Integer> orders;

   String groupName;

   public Pageable getPageable(){
      return PageRequest.of(pageNumber, pageSize, getSort());
   }

   public Sort getSort(){
      if(orders != null && !orders.isEmpty()){
         Set<String> nameSet = orders.keySet();
         ArrayList<Sort.Order> orderList = new ArrayList<>();
         for (String name : nameSet) {
            orderList.add(new Sort.Order(this.orders.get(name) == ASC ? Sort.Direction.ASC : Sort.Direction.DESC, name));
         }
         return Sort.by(orderList);
      }
      return Sort.unsorted();
   }

   public <T extends Base> Path getGroupName(Root<T> root){
      if (StringUtils.isNotBlank(this.groupName)) {
         String[] split = this.groupName.split("\\.");
         Path path = root;
         for (String s : split) {
            path = path.get(s);
         }
         return path;
      }
      return null;
   }
}
